package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.ICartService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSkuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class  CartServiceImpl implements ICartService {

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void addToCart(Long skuId, Integer skuNum) {

        //判断商品在购物车中是否存在
        Long userId = SecurityUtils.getUserId();
        String cartKey = getCartKey(userId);
        /*HashOperations hashOperations = redisTemplate.opsForHash();
        //redis的key，hash的key
        CartInfo cartInfo = (CartInfo)hashOperations.get(cartKey, skuId.toString());*/

        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        String hashKey = skuId.toString();

        if(hashOps.hasKey(hashKey)){
            //如果存在，则从购物车中获取商品信息，并将其数量+1
            CartInfo cartInfo = hashOps.get(hashKey);
            int totalNum = cartInfo.getSkuNum() + skuNum;
            cartInfo.setSkuNum(totalNum > 99 ? 99 : totalNum);
            hashOps.put(hashKey, cartInfo);

        }else{

            //判断购物车商品种类（不同SKU）总数大于50件
            Long count = hashOps.size();
            if(count >= 3){
                throw new ServiceException("购物车商品种类总数不能大于3件");
            }

            //如果不存在，则远程获取商品信息，将其加入到购物车中
            R<ProductSkuVo> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if(R.FAIL == productSkuResult.getCode()){
                throw new ServiceException("远程调用失败：" + productSkuResult.getMsg());
            }
            ProductSkuVo productSku = productSkuResult.getData();

            //组装CartInfo
            CartInfo cartInfo = new CartInfo();
            cartInfo.setSkuId(skuId);
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setThumbImg(productSku.getThumbImg());
            cartInfo.setSkuNum(skuNum); //商品数量
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuPrice(productSku.getSalePrice());
            cartInfo.setUserId(userId);
            cartInfo.setIsChecked(1);//默认选中
            cartInfo.setCreateTime(new Date());
            hashOps.put(hashKey, cartInfo);
        }

    }

    @Override
    public List<CartInfo> getCartList() {

        Long userId = SecurityUtils.getUserId();
        String cartKey = getCartKey(userId);

        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = hashOps.values();
        if(!CollectionUtils.isEmpty(cartInfoList)){
            cartInfoList = cartInfoList.stream().sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                    .toList();
        }
        return cartInfoList;
    }

    @Override
    public void deleteCart(Long skuId) {

        Long userId = SecurityUtils.getUserId();
        String cartKey = getCartKey(userId);

        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        hashOps.delete(skuId.toString());
    }

    @Override
    public void checkCart(Long skuId, Integer isChecked) {

        Long userId = SecurityUtils.getUserId();
        String cartKey = getCartKey(userId);

        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);

        String hashKey = skuId.toString();
        if (hashOps.hasKey(hashKey)) {
            CartInfo cartInfo = hashOps.get(hashKey);
            cartInfo.setIsChecked(isChecked);
            hashOps.put(hashKey, cartInfo);
        }
    }

    @Override
    public void allCheckCart(Integer isChecked) {

        Long userId = SecurityUtils.getUserId();
        String cartKey = getCartKey(userId);

        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> values = hashOps.values();
        if(!CollectionUtils.isEmpty(values)){
            for (CartInfo cartInfo : values) {
                cartInfo.setIsChecked(isChecked);
                hashOps.put(cartInfo.getSkuId().toString(), cartInfo);
            }
        }
    }

    @Override
    public void clearCart() {
        Long userId = SecurityUtils.getUserId();
        String cartKey = getCartKey(userId);

        redisTemplate.delete(cartKey);
    }

    /**
     * 组装购物车key
     * @param userId
     * @return
     */
    private String getCartKey(Long userId) {
        //定义key user:userId:cart
        return "user:cart:" + userId;
    }
}
